package com.office.config;

import com.alibaba.fastjson.JSON;
import com.office.personalOffice.personalInfo.dao.IPersonalInfo;
import com.office.personalOffice.personalInfo.model.ResponseResult;
import com.office.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author shkstart
 * @create 2022-11-07 16:07
 */
@Component
public class ChatAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
//        String loginAcct = httpServletRequest.getParameter("loginAcct");
//        System.out.println("onAuthenticationFailure,loginAcct:"+loginAcct);
        httpServletResponse.setCharacterEncoding("UTF-8");
        // 获取异常信息
        String message = e.getMessage();

        // 封装异常信息
        ResponseResult<Object> resultEntity = new ResponseResult<>(400,message);
        // 由于我是在前端异步访问登录，所以返回json数据
        // 如果是不是json交互，那么就在request中添加异常信息，在spring security配置文件中配置错误页面跳转并显示异常信息


        // 发送json数据
        PrintWriter out = httpServletResponse.getWriter();
        String json = JSON.toJSONString(resultEntity);
        out.write(json);
        out.flush();
        out.close();
    }
}

